let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class 沪深港通每日机构南向Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/07日沪深港通/沪深港通每日机构_南向/`;
        this.encode = 'UTF-8'
        this.params = {
            pageIndex: 1,
            date: '2015-01-01'
        }

        this.pageTotal = '';

        this.data = []
    }
    /**
     * 获取url
     */
    getUrl(date) {
        return `http://dcfm.eastmoney.com//em_mutisvcexpandinterface/api/js/get?type=HSGTCOMSTA&token=70f12f2f4f091e459a279469fe49eca5&st=HDDATE,SHAREHOLDCOUNT&sr=3&p=${this.params.pageIndex}&ps=50&js=var%20CRjxVBYt={pages:(tp),data:(x)}&filter=(MARKET=%27S%27)(HDDATE=^${this.params.date}^)&rt=51103998`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('13沪深港通每日机构_南向Controller')
        //--------------------
        if (new Date() >= new Date(this.params.date)) {
            if (this.pageTotal === '' || this.params.pageIndex <= this.pageTotal) {
                console.log(JSON.stringify(this.params))
                let result = await this.getData('', this.isCache)
                result = this.axiosDataFormat(result.toString());
                let pageDate = result.data;
                this.pageTotal = result.pages || 0
                this.params.pageTotal = this.pageTotal
                this.data = [...this.data, ...pageDate]
                this.params.pageIndex++;
            } else {
                this.writeCsv(this.data);
                this.data = [];
                this.pageTotal = ''
                this.params.pageIndex = 1;
                this.params.date = new Date(this.addDate(this.params.date, 1)).format('yyyy-MM-dd')
            }
            await this.getHistory()
        }
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace(/^var\s\w+?\s*\=/, '').trim())
        } catch (err) {
            try {
                result = eval('(' + data.replace(/^var\s\w+?\s*\=/, '').trim() + ')')
            } catch (err) {
                if (data.indexOf('502 Bad Gateway') > -1) {
                    return []
                } else {
                    console.log(err)
                }

            }
        }
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        if (arr && arr.length) {
            fs.writeFileSync(path.join(this.baseSrc, `沪深港通每日机构_南向_${this.params.date.replace(/-/g, '')}_${new Date().format('yyyyMMdd')}.csv`), this.convertToCSV(arr, 'title'), 'UTF-8')
        }
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.params.date = new Date(startDate).format('yyyy-MM-dd');
        this.isCache = isCache;
        console.log('--->13沪深港通每日机构_南向Controller')
        await this.getHistory()
    }
}

let controller = new 沪深港通每日机构南向Controller()
module.exports = controller
